package org.megha.blog.example.singleton;

import java.util.HashMap;
import java.util.Map;

/**
 * Gives the Sum of squares till nth number.
 * It memoizes the results so that repeated calls are fast.
 *
 * @author megha birmiwal
 */
public class MemoizedSumOfSquares {

	private static MemoizedSumOfSquares singletonInstance = null;

	private final Map<Integer, Long> sumOfSquarePairs = new HashMap<Integer, Long>();

	private MemoizedSumOfSquares() {}

	// marking it synchronized, to prevent race conditions i.e. when multiple thread try to call this at the same time.
	public synchronized MemoizedSumOfSquares getInstance() {
		if  (singletonInstance == null) {
			singletonInstance = new MemoizedSumOfSquares();
		}
		return singletonInstance;
	}

	public long getSumOfSquares(int n) {
		if (n == 0) return 0;
		if (sumOfSquarePairs.containsKey(n)) {
			return sumOfSquarePairs.get(n);
		}
		long result = getSumOfSquares(n-1) + n*n;
		sumOfSquarePairs.put(n, result);
		return result;
	}
}
